#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from dws.commons.common import log
from common.util.check_utils import is_valid_id
from dws.commons.parse_param import parse_param_with_jsonschema
from common.common import exter_attack
from dws.backup.cluster_backup import ClusterBackup
from dws.commons.dws_param_parse import DwsParamParse
from dws.commons.job_info import JobInfo


@exter_attack
def do_exec(pid):
    log.info(f"Enter, pid:{pid}")
    param = parse_param_with_jsonschema(pid)

    job_info = JobInfo(pid=pid,
                       job_id=DwsParamParse.get_job_id(param),
                       sub_job_id=DwsParamParse.get_sub_job_id(param),
                       copy_id=DwsParamParse.get_copy_id(param),
                       backup_type=DwsParamParse.get_type(param),
                       meta_path=DwsParamParse.get_meta_path(param),
                       meta_rep=DwsParamParse.get_meta_rep(param),
                       cache_path=DwsParamParse.get_cache_path(param),
                       cache_rep=DwsParamParse.get_cache_rep(param),
                       data_reps=DwsParamParse.get_data_reps(param))
    log.info(f'{job_info}')

    try:
        if not ClusterBackup(pid).query_backup_copy(job_info):
            raise Exception("Query failed.")
    except Exception as err_str:
        log.error(f"Err: {err_str}, pid: {pid}, {job_info.log_format()}")
        return False
    log.info(f"Query suc, pid: {pid}, {job_info.log_format()}")
    return True


if __name__ == '__main__':
    """查询任务详情任务"""
    if not is_valid_id(sys.argv[1]):
        log.warn(f"pid is invalid")
        sys.exit(1)
    try:
        if not do_exec(sys.argv[1]):
            sys.exit(1)
    except Exception as err:
        log.error(f"Err: {err}, pid: {sys.argv[2]}")
        sys.exit(1)

    sys.exit(0)
